import { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Space,
  Card,
  Tag,
  Input,
  Select,
  Modal,
  message,
  Dropdown,
  Row,
  Col,
  Statistic,
} from 'antd';
import {
  EditOutlined,
  MoreOutlined,
  DollarOutlined,
  EyeOutlined,
} from '@ant-design/icons';
import useMembersStore from '../../store/members/useMembersStore';
import MemberForm from './MemberForm';
import RechargeForm from './RechargeForm';
import { MEMBER_LEVELS } from '../../constants/memberLevels';
import dayjs from 'dayjs';

const { Search } = Input;
const { Option } = Select;

const MembersList = () => {
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [rechargeModalVisible, setRechargeModalVisible] = useState(false);
  const [levelDetailModalVisible, setLevelDetailModalVisible] = useState(false);
  const [currentMember, setCurrentMember] = useState(null);
  const [searchPhone, setSearchPhone] = useState('');
  
  const {
    members,
    loading,
    filters,
    getMembers,
  } = useMembersStore();

  useEffect(() => {
    getMembers(filters);
  }, []);

  const levelsByValue = MEMBER_LEVELS.reduce((acc, level) => {
    acc[level.value] = level;
    return acc;
  }, {});

  const levelDistribution = MEMBER_LEVELS.reduce((acc, level) => {
    acc[level.value] = members.filter(m => m.level === level.value).length;
    return acc;
  }, {});

  const statistics = {
    total: members.length,
    levelDistribution
  };

  const columns = [
    {
      title: '会员 Slug',
      dataIndex: 'slug',
      key: 'slug',
      width: 150,
      render: (slug) => (
        <Tag color="cyan" style={{ fontWeight: 500 }}>{slug}</Tag>
      ),
    },
    {
      title: '会员信息',
      key: 'info',
      width: 200,
      render: (_, record) => (
        <Space direction="vertical" size={0}>
          <span style={{ fontWeight: 500, fontSize: 14 }}>{record.nickname}</span>
          <span style={{ fontSize: 12, color: '#999' }}>{record.phone}</span>
        </Space>
      ),
    },
    {
      title: '微信号',
      dataIndex: 'wechat',
      key: 'wechat',
      width: 150,
    },
    {
      title: '生日',
      dataIndex: 'birthday',
      key: 'birthday',
      width: 120,
      render: (birthday) => birthday ? dayjs(birthday).format('YYYY-MM-DD') : '-',
    },
    {
      title: '会员等级',
      dataIndex: 'level',
      key: 'level',
      width: 120,
      render: (level) => {
        const config = levelsByValue[level];
        return (
          <Tag color={config.color} style={{ fontWeight: 500 }}>
            {config.label}
          </Tag>
        );
      },
    },
    {
      title: '积分',
      dataIndex: 'points',
      key: 'points',
      width: 100,
      render: (points) => (
        <span style={{ fontWeight: 500, color: '#1890ff' }}>{points}</span>
      ),
    },
    {
      title: '余额',
      dataIndex: 'balance',
      key: 'balance',
      width: 120,
      render: (balance) => (
        <span style={{ fontWeight: 600, color: '#3f8600' }}>¥{balance.toFixed(2)}</span>
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      width: 180,
      render: (time) => dayjs(time).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 120,
      render: (_, record) => {
        const items = [
          {
            key: 'edit',
            label: '编辑信息',
            icon: <EditOutlined />,
            onClick: () => handleEdit(record),
          },
          {
            type: 'divider',
          },
          {
            key: 'recharge',
            label: '充值',
            icon: <DollarOutlined />,
            onClick: () => handleRecharge(record),
          },
        ];

        return (
          <Dropdown
            menu={{ items }}
            trigger={['click']}
          >
            <Button type="text" icon={<MoreOutlined />} />
          </Dropdown>
        );
      },
    },
  ];

  const handleEdit = (record) => {
    setCurrentMember(record);
    setEditModalVisible(true);
  };

  const handleRecharge = (record) => {
    setCurrentMember(record);
    setRechargeModalVisible(true);
  };

  const handleLevelFilter = (level) => {
    getMembers({ level });
  };

  const handleSearch = (value) => {
    setSearchPhone(value);
    getMembers({ ...filters, phone: value });
  };

  const filteredMembers = searchPhone
    ? members.filter(member => member.phone.includes(searchPhone))
    : members;

  return (
    <div className="p-6">
      <Row gutter={16} className="mb-6">
        <Col span={6}>
          <Card>
            <Statistic
              title="全部会员"
              value={statistics.total}
            />
          </Card>
        </Col>
        <Col span={18}>
          <Card>
            <Statistic
              title={
                <Space>
                  <span>等级分布</span>
                  <Button
                    type="link"
                    size="small"
                    icon={<EyeOutlined />}
                    onClick={() => setLevelDetailModalVisible(true)}
                    style={{ padding: 0 }}
                  >
                    查看详情
                  </Button>
                </Space>
              }
              value={Object.keys(statistics.levelDistribution).length}
            />
          </Card>
        </Col>
      </Row>

      <Card>
        <div style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Space size={12}>
            <Select
              value={filters.level}
              style={{ width: 140 }}
              onChange={handleLevelFilter}
            >
              <Option value="all">全部等级</Option>
              {MEMBER_LEVELS.map(level => (
                <Option key={level.value} value={level.value}>{level.label}</Option>
              ))}
            </Select>
            <Search
              placeholder="搜索手机号"
              allowClear
              onSearch={handleSearch}
              style={{ width: 250 }}
            />
          </Space>
        </div>

        <Table
          columns={columns}
          dataSource={filteredMembers}
          rowKey="id"
          loading={loading}
          pagination={{
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条`,
            defaultPageSize: 10,
          }}
          scroll={{ x: 1200 }}
        />
      </Card>

      <Modal
        title="编辑会员信息"
        open={editModalVisible}
        onCancel={() => {
          setEditModalVisible(false);
          setCurrentMember(null);
        }}
        footer={null}
        width={700}
        destroyOnClose
      >
        <MemberForm
          member={currentMember}
          onSuccess={() => {
            setEditModalVisible(false);
            setCurrentMember(null);
            getMembers(filters);
          }}
          onCancel={() => {
            setEditModalVisible(false);
            setCurrentMember(null);
          }}
        />
      </Modal>

      <Modal
        title="会员充值"
        open={rechargeModalVisible}
        onCancel={() => {
          setRechargeModalVisible(false);
          setCurrentMember(null);
        }}
        footer={null}
        width={600}
        destroyOnClose
      >
        <RechargeForm
          member={currentMember}
          onSuccess={() => {
            setRechargeModalVisible(false);
            setCurrentMember(null);
            getMembers(filters);
          }}
          onCancel={() => {
            setRechargeModalVisible(false);
            setCurrentMember(null);
          }}
        />
      </Modal>

      <Modal
        title="等级分布详情"
        open={levelDetailModalVisible}
        onCancel={() => setLevelDetailModalVisible(false)}
        footer={null}
        width={600}
      >
        <Space direction="vertical" size={12} style={{ width: '100%' }}>
          {MEMBER_LEVELS.map(level => (
            <div 
              key={level.value} 
              style={{ 
                display: 'flex', 
                justifyContent: 'space-between', 
                alignItems: 'center',
                padding: '12px 16px',
                background: '#f5f5f5',
                borderRadius: '8px',
                transition: 'all 0.2s'
              }}
              onMouseEnter={(e) => e.currentTarget.style.background = '#e6f4ff'}
              onMouseLeave={(e) => e.currentTarget.style.background = '#f5f5f5'}
            >
              <Space>
                <Tag color={level.color} style={{ margin: 0 }}>{level.label}</Tag>
                <span style={{ fontSize: 12, color: '#999' }}>
                  ({level.minPoints}-{level.maxPoints === Infinity ? '∞' : level.maxPoints})
                </span>
              </Space>
              <span style={{ fontWeight: 600, fontSize: 18, color: '#1890ff' }}>
                {statistics.levelDistribution[level.value] || 0}
              </span>
            </div>
          ))}
        </Space>
      </Modal>
    </div>
  );
};

export default MembersList;
